#!/bin/bash

apt -y install xinetd
apt -y install curl

sh -c "echo '
service post2prosody
{
 disable = no
 type = UNLISTED
 socket_type = stream
 wait = no
 user = root
 protocol = tcp
 port = 80
 server = /bin/bash
 server_args = /usr/local/bin/post2prosody.sh
 per_source = UNLIMITED
 instances = UNLIMITED
 cps = 1000 1
 log_type = FILE /dev/null
}
' > /etc/xinetd.d/post2prosody"

sh -c "echo '#!/bin/bash

DIR=/var/log
FILE=\$(basename \$0)
FILE=\${FILE%.*}
FOES=\$FILE.foes.log
FILE=\$FILE.\$PPID

rm -f \$DIR/\$FILE.* 2> /dev/null > /dev/null

timeout 1 dd bs=1 count=512 of=\$DIR/\$FILE.msg 2> /dev/null
find \$DIR -iname \$FILE.msg -size -32c -delete 2> /dev/null > /dev/null

if [ -r \$DIR/\$FILE.msg ]
then

sed -n \"1{/^POST\\ /p}\" \$DIR/\$FILE.msg > \$DIR/\$FILE.post

if [ -s \$DIR/\$FILE.post ]
then

csplit -f \$DIR/\$FILE. \$DIR/\$FILE.msg /^.\$/+1
sed -n -e \"/&/p\" -e \"/=/p\" -e \"/%/p\" -e \"/--/p\" -e \"/}/p\" -e \"/<!/p\" -e \"/<[?]/p\" -e \"/--/p\" -e \"/http:/p\" -e \"/https:/p\" \$DIR/\$FILE.01 > \$DIR/\$FILE.02

if [ -s \$DIR/\$FILE.01 ] && ! [ -s \$DIR/\$FILE.02 ]
then

curl http://localhost:5280/msg/cli@jf.me -u srv@jf.me:'$(cat $ROOT_PATH/cfg/xmpp.srv.secret)' -H \"Content-Type: text/plain\" -d @\$DIR/\$FILE.01
rm -f \$DIR/\$FILE.* 2> /dev/null > /dev/null
exit

fi
fi
fi

echo \$REMOTE_HOST >> \$DIR/\$FOES

rm -f \$DIR/\$FILE.* 2> /dev/null > /dev/null
' > /usr/local/bin/post2prosody.sh"

service xinetd restart

### iptables ###

iptables -A INPUT -m tcp -p tcp --dport 80 -j ACCEPT

netfilter-persistent save

### fail2ban ###

sh -c "echo '
# Fail2Ban configuration file for prosody authentication
[Definition]
failregex = :ffff:<HOST>
ignoreregex =
' > /etc/fail2ban/filter.d/post2prosody.conf"

sh -c "echo '
[post2prosody]
enabled = true
port    = 80
filter  = post2prosody
logpath = /var/log/post2prosody.foes.log
maxretry = 5
bantime = 24h
findtime = 5m
' > /etc/fail2ban/jail.d/post2prosody.conf"

touch /var/log/post2prosody.foes.log

service fail2ban restart
